<template>
  <div class="invite-box">
    <el-drawer
      title="邀请新用户"
      :visible="isOpen"
      :direction="direction"
      @close="handleClose"
      size="28%"
    >
      <el-tabs
        @hook:mounted="getCanvas"
        v-model="activeName"
        type="border-card"
        @tab-click="handleClick"
      >
        <el-tab-pane label="二维码" name="Qa" v-hasPermi="['work:commercialManager:obtain']">
          <div class="scanQr" ref="scanQr" id="scanQr">
            <el-avatar
              :size="40"
              :src="
                userInfo.avatar || require('@/assets/images/defaultAvatar.jpg')
              "
            ></el-avatar>
            <span>{{ userInfo.nickName }} 邀请您注册</span>
            <p>问三师</p>
            <canvas
              id="canvas"
              ref="canvas"
              style="height: 200px; width: 200px"
            ></canvas>
            <!-- <span
              >二维码失效时间为:2022年6月18日<span class="reset"
                >重置</span
              ></span -->
            <!-- > -->
            <span>请使用微信扫描二维码</span>
          </div>
        </el-tab-pane>
        <el-tab-pane
          v-hasPermi="['work:commercialManager:inviteJoin']"
          class="phoneNumber"
          label="手机号"
          name="phoneNumber"
        >
          <div class="phone">
            <p class="tip">输入手机号添加成员。添加后，对方将收到短信通知</p>
            <div class="input-item">
              <el-form :model="phoneObject" ref="form" class="demo-dynamic">
                <el-form-item
                  v-for="(item, index) in phoneObject.items"
                  :label="''"
                  :key="index"
                  :prop="'items.' + index + '.phone'"
                  :rules="{
                    required: true,

                    trigger: 'blur',
                    validator: validatePass,
                  }"
                >
                  <el-input
                    placeholder="请输入手机号"
                    v-model="item.phone"
                  ></el-input>
                  <i
                    class="el-icon-remove"
                    @click.prevent="removePhone(item)"
                  ></i>
                </el-form-item>
              </el-form>
            </div>
            <span class="ContinueToAdd" @click="addPhone">+ 继续添加</span>
          </div>
        </el-tab-pane>

        <SubBtn>
          <template slot="btn" v-if="activeName == 'Qa'">
            <el-button round class="elBtn" @click="handleClose()">取消</el-button>
            <el-button type="primary" class="save" @click="handleSniPastImg" round>保存</el-button>
            <!-- <el-button type="primary" class="copy" @click="handleSniPastCopy" round>复制</el-button> -->
          </template>
          <template slot="btn" v-else>
            <el-button round class="elBtn" @click="handleClose()">取消</el-button>
            <el-button round type="primary" class="defaultBtn" @click="sendFn">发送</el-button>
          </template>
        </SubBtn>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script>
import { jsPDF } from "jspdf";
import html2canvas from "html2canvas";
import SubBtn from "@/wss/components/subBtn.vue";
import { updateGetRoleIdApi } from "@/api/system/user.js";
import { mapGetters } from "vuex";
import { getcommercialManagerInviteJoinApi,getCommercialManagerObtainApi } from "@/wss/newApi_3-24/work/commercialManager.js";
import { dataURLToBlob } from "@/wss/utils/wss.js";
export default {
  components: { SubBtn },
  props: {
    getcommercialManagerPlaceOfUserFn: {
      type: Function,
      default: () => {},
    },
    isOpen: {
      type: Boolean,
      default() {
        return false;
      },
    },
    
  },
  data() {
    return {
      phoneObject: {
        items: [
          {
            phone: "",
            type: 2,
          },
        ],
      },
      userRole: {},
      circleUrl: "",
      activeName: "Qa",
      direction: "rtl",
      
      cmId:'',//商务id
      placeId:'',//渠道id
    };
  },

  computed: {
    ...mapGetters(["userInfo"]),
  },
  methods: {
    async updateGetRoleIdFn() {
      // 这个接口开发时，后端人员比要忙，没有写接口文档
      let resutl = await updateGetRoleIdApi();
      if (resutl.code != 200) return;

      this.userRole = resutl;
      console.log(this.userRole, "那个姓名");
    },

    // 获取渠道和商务id
    async getCommercialManagerObtain(){
      let result = await getCommercialManagerObtainApi()
      if(result.code==200){
        this.cmId = result.cmId
        this.placeId = result.placeId
      }
    },

    // 生成二维码
    async getCanvas() {
      var QRCode = require("qrcode");

      await this.getCommercialManagerObtain(); // 获取渠道和商务id

      let { organizationId = null } = this.$store.getters.userInfo;
      let { placeId = null, cmId = null } = this.userRole;
      let href = 'm.wensanshi.com' //获取当前域名 不带http://
      let nickName = this.userInfo.nickName
      console.log(`http://${href}/pages/invite/register/index?placeId=${this.placeId}&cmId=${this.cmId}&organizationId=${organizationId}&nickName=${nickName}`);
      // 线下地址
      if (process.env.VUE_APP_BASE_API == "/dev-api") {
        QRCode.toCanvas(
          this.$refs.canvas,
          `http://${href}/pages/invite/register/index?placeId=${this.placeId}&cmId=${this.cmId}&organizationId=${organizationId}&nickName=${nickName}`,
          function (error) {
            if (error) console.error(error);
            console.log("success!");
          }
        );
        // 线上地址
      } else {
        QRCode.toCanvas(
          this.$refs.canvas,
          `http://${href}/pages/invite/register/index?placeId=${this.placeId}&cmId=${this.cmId}&organizationId=${organizationId}&nickName=${nickName}`,
          function (error) {
            if (error) console.error(error);
            console.log("success!");
          }
        );
      }
    },

    // 点击保存为图片
    handleSniPast() {
      const dom = window.document.querySelector(".scanQr");
      var width = dom.offsetWidth; //dom宽
      var height = dom.offsetHeight; //dom高
      var scale = 1; //放大倍数

      if (dom) {
        html2canvas(dom, {
          useCORS: true,
          dpi: window.devicePixelRatio * 2,
          scale: scale,
          width: width,
          heigth: height,
        }).then((canvas) => {
          //通过html2canvas将html渲染成canvas，然后获取图片数据
          var imgData = canvas.toDataURL("image/jpeg");

          //初始化pdf，设置相应格式
          var doc = new jsPDF("p", "mm", "a4");

          //这里设置的是a4纸张尺寸
          doc.addImage(imgData, "JPEG", 0, 0, 210, 297);

          //输出保存命名为content的pdf
          doc.save(`test.pdf`);
        });
      }
    },

    // ******************************保存复制按钮******************************
    // 保存为图片
    handleSniPastImg() {
      let _this = this;
      this.$message({ message: "正在保存，请稍等！", type: "success" });
      // 第一个参数为需要保存的div的id名 第二个参数为保存图片的名称 第三个为当前的操作download下载copy复制
      setTimeout(() => {
        _this.saveImage("scanQr", "问三师邀请二维码", "download");
      }, 10);
    },
    // 复制图片到剪切板
    handleSniPastCopy() {
      let _this = this;
      this.$message({ message: "正在复制，请稍等！", type: "success" });
      // 第一个参数为需要保存的div的id名 第二个参数为保存图片的名称 第三个为当前的操作download下载copy复制
      setTimeout(() => {
        _this.saveImage("scanQr", "问三师邀请二维码", "copy");
      }, 10);
    },

    /*保存图片的方法（即按钮点击触发的方法）第一个参数为需要保存的div的id名 第二个参数为保存图片的名称 */
    saveImage(divText, imgText, action) {
      let scale=2;//缩放比例
      let canvasID = this.$refs[divText];
      let width = canvasID.offsetWidth; //dom宽
      let height = canvasID.offsetHeight; //dom高
      // 配置
      let option = {
        dpi: 300,
        scale: scale,
        width: width,
        heigth: height,
      }
      let a = document.createElement("a");
      html2canvas(canvasID,option).then((canvas) => {
        let dom = document.body.appendChild(canvas);
        dom.style.display = "none";
        a.style.display = "none";
        document.body.removeChild(dom);
        let blob = dataURLToBlob(dom.toDataURL("image/png"));
        if (action == "download") {
          a.setAttribute("href", URL.createObjectURL(blob));
          //这块是保存图片操作  可以设置保存的图片的信息
          a.setAttribute("download", imgText + ".png");
          document.body.appendChild(a);
          a.click();
          URL.revokeObjectURL(blob);
          document.body.removeChild(a);
          //这块是保存图片操作  可以设置保存的图片的信息 end
        } else {
          //这块是复制到剪切板图片操作
          // clipboard.write 仅支持image/png的blob数据
          navigator.clipboard.write([
            new window.ClipboardItem({
              [blob.type]: blob,
            }),
          ]);
          this.$message({ message: "复制成功！", type: "success" });
          //这块是复制到剪切板图片操作end
        }
      });
    },
    // ******************************保存复制按钮******************************end

    // 保存手机号
    async sendFn() {
      await this.$refs.form.validate();
      const { items } = this.phoneObject;
      let phone = items.map((item) => item.phone).join();

      let { code, data } = await getcommercialManagerInviteJoinApi({
        phone,
        type: 2,
      });
      if (code != 200) return;
      this.getcommercialManagerPlaceOfUserFn();
      this.$emit("update:isOpen", false);

      this.$message({
        type: "success",
        message: `成功${data}`,
      });
      this.phoneObject = {
        items: [
          {
            phone: "",
            type: 2,
          },
        ],
      };
    },
    // 去除输入框
    removePhone(item) {
      var index = this.phoneObject.items.indexOf(item);
      if (index !== -1) {
        this.phoneObject.items.splice(index, 1);
      }
    },
    validatePass(rule, value, callback) {
      console.log(value, "搞定了");
      if (!/^1[3456789]\d{9}$/.test(value)) {
        callback(new Error("手机号非法"));
      } else {
        callback();
      }
    },
    // 新增输入框
    addPhone() {
      if (this.phoneObject.items.length >= 5) {
        return;
      }
      this.phoneObject.items.push({
        phone: "",
        type: 2,
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleClose() {
      this.$emit("update:isOpen", false);
    },
  },
};
</script>

<style lang="scss" scoped>
/* 未开票样式 */
.notInvoiced {
  padding: 30px 30px 0;
}
.notInvoiced ul {
  margin-bottom: 40px;
}
.notInvoiced .el-checkbox {
  margin-right: 10px;
}
::v-deep .notInvoiced .el-checkbox__label {
  display: none;
}

::v-deep .notInvoiced .el-checkbox .el-checkbox__inner {
  width: 24px;
  height: 24px;
  border-color: #bbbbbb;
  background: #fff;
  border-radius: 50%;
}
::v-deep .notInvoiced .el-checkbox .is-disabled .el-checkbox__inner {
  background: #f2f2f2;
}
::v-deep .notInvoiced .el-checkbox .is-checked .el-checkbox__inner {
  border-color: #f87a23;
  background: #f87a23;
}
::v-deep .notInvoiced .el-checkbox__input .el-checkbox__inner::after {
  content: "";
  width: 11px;
  height: 6px;
  border: 3px solid white;
  border-top: transparent;
  border-right: transparent;
  text-align: center;
  display: block;
  position: absolute;
  top: 6px;
  left: 5px;
  vertical-align: middle;
  transform: rotate(0deg) scaleY(0);
  border-radius: 0px;
  background: none;
}
::v-deep
  .notInvoiced
  .el-checkbox__input.is-checked
  .el-checkbox__inner::after {
  transform: rotate(-45deg) scaleY(1);
}
.notInvoiced .invInfo {
  flex-grow: 1;
  border-bottom: 1px solid #efefef;
  margin-bottom: 20px;
  padding-bottom: 20px;
}

.notInvoiced li {
  display: flex;
}
/* .notInvoiced ul > li:hover {
  background-color: #f4f5f8;
} */

.notInvoiced li h3 {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 0;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  margin-top: 3px;
}
.notInvoiced li h3 > span {
  font-weight: 400;
  font-size: 12px;
  color: #999;
}
.notInvoiced li p {
  margin: 0;
  font-size: 12px;
  color: #999;
  line-height: 20px;
}
.allSelectBox {
  align-items: center;
  justify-content: space-between;
  display: flex;
}
.cashAmount {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.cashAmount p {
  color: #39486f;
  font-size: 30px;
  font-weight: bold;
}
.cashAmount .el-button {
  border-color: #f87a23;
  color: #f87a23;
  font-weight: bold;
  font-size: 14px;
}
.cashAmount .el-button.cashIsFocus,
.cashAmount .el-button:hover {
  background-color: #f87a23;
  color: #fff;
}
::v-deep .el-tabs__content {
  height: calc(100% - 53px);
  padding: 0px;
}
::v-deep .el-tabs__content .el-tab-pane {
  height: 100%;
}
::v-deep .el-tabs {
  padding: 0px !important;
  height: 100%;
  border: unset;
  box-shadow: unset;
}
.el-tabs__content {
  position: relative;
}
.phoneNumber {
  .button-box {
    right: 0;
    bottom: 0px;
    position: absolute;
    display: flex;
    width: 100%;
    border-top: solid 1px #f0f2f5;
    padding-top: 20px;
    justify-content: flex-end;
    .defaultBtn {
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #ffffff;
      padding: 8px 20px;
      background-color: #f87a23;
      border-color: #f87a23;
      cursor: pointer;
    }
    .elBtn {
      font-size: 14px;
      font-family: PingFangSC-Semibold, PingFang SC;
      font-weight: 600;
      color: #606e84;
      padding: 8px 20px;
    }
  }
}

// 二维码
.scanQr {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  padding-bottom: 80px;
  background: url("~@/wss/assets/image/dt_img.png") center no-repeat;
  background-size: cover;
}
.scanQr .el-avatar {
  margin: 15px;
}

.scanQr img {
  width: 150px;
  margin: 15px;
}
.scanQr p {
  font-size: 18px;
  font-weight: bold;
  color: #2e3f5e;
}
.scanQr span {
  font-size: 12px;
  color: #999;
}
.scanQr span .reset {
  font-size: 12px;
  color: #f87a23;
  margin-left: 10px;
}
::v-deep .el-tabs__content {
  position: unset;
}

.ContinueToAdd {
  cursor: pointer;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #f87a23;
}
.input-item {
}
::v-deep .input-item .el-form .el-form-item__content {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}
.el-input--medium {
  width: calc(100% - 32px);
}
::v-deep .input-item .el-form .el-form-item__content > i {
  width: 16px;
  margin-left: 16px;
}

::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}
.el-tabs--border-card > .el-tabs__content {
  padding: 15px;
}

.phone {
  padding: 0 20px;
}
.tip {
  font-size: 12px;
  color: #999999;
}
::v-deep .el-tabs--border-card > .el-tabs__header {
  display: none;
  background-color: #f5f7fa;
  border-bottom: 1px solid #dfe4ed;
  margin: 0;
  margin: 0 auto;
}
::v-deep .el-tabs {
  padding: 0px 30px;
}
::v-deep .el-tabs__nav {
  white-space: nowrap;
  position: relative;
  transition: transform 0.3s;
  float: left;
  z-index: 2;
  width: 100%;
  display: flex;
  justify-content: space-between;
}
::v-deep .el-tabs__nav-scroll {
  margin: 10px 20px;
  border: 1px solid #f0f2f5;

  border-radius: 4px;
}
::v-deep .el-tabs__item {
  text-align: center;
  flex: 1;
  height: 32px;
  line-height: 32px;
  font-weight: bold;
  background: #f0f2f5;
  border-radius: 2px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #2e3f5e;
  border: 1px solid #2e3f5e;
}
::v-deep .el-tabs__item .is-top {
  background: #ffffff;
}
::v-deep .el-tabs__nav-wrap {
  margin-left: 0px;
}
::v-deep .el-tabs--border-card > .el-tabs__header {
  background-color: unset;
  border: unset;
}
::v-deep .el-tabs--border-card > .el-tabs__header .el-tabs__item {
  border: unset;
  font-weight: bold;
  color: #2e3f5e;
}
.el-icon-remove {
  width: 14px;
  height: 14px;
}
::v-deep .el-icon-remove:before {
  color: #909aaa;
}

::v-deep .input-with-select.el-input.is-disabled .el-input__inner {
  color: #333;
  cursor: text;
}
::v-deep .el-drawer__header {
  display: flex !important;
  flex-wrap: wrap;
  border-bottom: 1px solid #efefef;
  padding-bottom: 15px;
  margin-bottom: 0px;
}
::v-deep .el-drawer__header > span {
  font-size: 18px;
  font-weight: bold;
  color: #2e3f5e;
  padding-left: 20px;
  background: url("~@/wss/assets/image/icon/cardLeft.png") left center no-repeat;
  background-size: 7px;
}
::v-deep .el-drawer__body {
  padding: 0px;
}
::v-deep .el-drawer__header {
  border-bottom: unset;
  display: unset;
}
::v-deep .el-drawer__header::after {
  width: 95%;
  height: 1px;
  background-color: #909aaa;
  display: block;
  content: "";
  margin: 0 auto;
  margin-top: 10px;
}
.footer {
  right: 20px;
  position: absolute;
  bottom: 20px;

  .copy {
    width: 120px;
    height: 40px;
    background: #f87a23;
    border-radius: 20px;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #ffffff;
  }
  .save {
    width: 120px;
    height: 40px;

    border-radius: 20px;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #606e84;
  }
}

/* 右侧按钮样式 */
::v-deep .subBtn {
  padding: 8px 30px;
}
::v-deep .subBtn .el-button {
  width: 100px;
  padding: 8px 0;
  font-size: 14px;
  color: #606e84;
}
::v-deep .subBtn .el-button--primary {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
::v-deep .subBtn .el-button--primary:hover {
  background-color: #f87a23;
  border-color: #f87a23;
  color: #fff;
}
</style>
